package com.largeOrange.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.largeOrange.common.R;
import com.largeOrange.dto.SetMealDto;
import com.largeOrange.mapper.SetMealMapper;
import com.largeOrange.pojo.Setmeal;
import com.largeOrange.pojo.SetmealDish;
import com.largeOrange.service.SetMealDishService;
import com.largeOrange.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

/**
 * @author 大橙子
 * @version 1.0
 * @since 1.0
 */
@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {

    @Autowired
    private SetMealDishService setMealDishService;

    /**
     * 套餐保存
     * @param setMealDto
     */
    @Override
    @Transactional
    public void saveSetMealAndDish(SetMealDto setMealDto) {
        //setMeal表数据保存
        this.save(setMealDto);
        Long id = setMealDto.getId();
        List<SetmealDish> setMealDishes = setMealDto.getSetmealDishes();
        setMealDishes.forEach(setMealDish -> {
            setMealDish.setSetmealId(id);
            setMealDishService.save(setMealDish);
        });
    }

    /**
     * 套餐修改
     * @param setMealDto
     */
    @Override
    @Transactional
    public void updateTwoForms(SetMealDto setMealDto) {
        //先删除表中数据
        //setMeal表
        this.removeById(setMealDto.getId());
        //setMealDish表
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,setMealDto.getId());
        setMealDishService.remove(wrapper);
        //保存
        this.saveSetMealAndDish(setMealDto);
    }

    /**
     * 套餐批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void deleteAllByIds(Long[] ids) {
        for (Long id : ids) {
            //先删除setMeal表
            this.removeById(id);
            //删除setMealDish表
            LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SetmealDish::getSetmealId,id);
            setMealDishService.remove(wrapper);
        }
    }
}
